<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="format-detection" content="telephone=no"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-status-bar-style" content="black"><link rel="icon" href="/images/icons/favicon-16x16.png?v=2.6.2" type="image/png" sizes="16x16"><link rel="icon" href="/images/icons/favicon-32x32.png?v=2.6.2" type="image/png" sizes="32x32"><meta name="description" content="#相关概念  程序(program)是为完成特定任务、用某种语言编写的一组指令的集合。即指一 段静态的代码，静态对象。">
<meta property="og:type" content="article">
<meta property="og:title" content="java-Thread">
<meta property="og:url" content="https://kohler19.gitee.io/2022/04/02/java-Thread/index.html">
<meta property="og:site_name" content="愷龍的网络日志">
<meta property="og:description" content="#相关概念  程序(program)是为完成特定任务、用某种语言编写的一组指令的集合。即指一 段静态的代码，静态对象。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://pic.imgdb.cn/item/6247ff2d27f86abb2a9097a8.jpg">
<meta property="og:image" content="https://pic.imgdb.cn/item/6247ff6f27f86abb2a913cf8.jpg">
<meta property="og:image" content="https://pic.imgdb.cn/item/6248027627f86abb2a97aa0c.jpg">
<meta property="og:image" content="https://pic.imgdb.cn/item/624802a727f86abb2a9815a1.jpg">
<meta property="article:published_time" content="2022-04-02T07:37:13.000Z">
<meta property="article:modified_time" content="2022-04-05T02:38:22.781Z">
<meta property="article:author" content="李恺龙">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://pic.imgdb.cn/item/6247ff2d27f86abb2a9097a8.jpg"><title>java-Thread | 愷龍的网络日志</title><link ref="canonical" href="https://kohler19.gitee.io/2022/04/02/java-Thread/"><link rel="dns-prefetch" href="https://cdn.jsdelivr.net"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.12.1/css/all.min.css" type="text/css"><link rel="stylesheet" href="/css/index.css?v=2.6.2"><script>var Stun = window.Stun || {};
var CONFIG = {
  root: '/',
  algolia: undefined,
  assistSearch: undefined,
  fontIcon: {"prompt":{"success":"fas fa-check-circle","info":"fas fa-arrow-circle-right","warning":"fas fa-exclamation-circle","error":"fas fa-times-circle"},"copyBtn":"fas fa-copy"},
  sidebar: {"offsetTop":"20px","tocMaxDepth":6},
  header: {"enable":true,"showOnPost":true,"scrollDownIcon":false},
  postWidget: {"endText":true},
  nightMode: {"enable":true},
  back2top: {"enable":true},
  codeblock: {"style":"default","highlight":"light","wordWrap":false},
  reward: false,
  fancybox: false,
  zoomImage: {"gapAside":"20px"},
  galleryWaterfall: undefined,
  lazyload: false,
  pjax: undefined,
  externalLink: {"icon":{"enable":true,"name":"fas fa-external-link-alt"}},
  shortcuts: undefined,
  prompt: {"copyButton":"复制","copySuccess":"复制成功","copyError":"复制失败"},
  sourcePath: {"js":"js","css":"css","images":"images"},
};

window.CONFIG = CONFIG;</script><meta name="generator" content="Hexo 5.4.0"></head><body><div class="container" id="container"><header class="header" id="header"><div class="header-inner"><nav class="header-nav header-nav--fixed"><div class="header-nav-inner"><div class="header-nav-menubtn"><i class="fas fa-bars"></i></div><div class="header-nav-menu"><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/"><span class="header-nav-menu-item__icon"><i class="fas fa-home"></i></span><span class="header-nav-menu-item__text">首页</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/archives/"><span class="header-nav-menu-item__icon"><i class="fas fa-folder-open"></i></span><span class="header-nav-menu-item__text">归档</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/分类/"><span class="header-nav-menu-item__icon"><i class="fas fa-layer-group"></i></span><span class="header-nav-menu-item__text">分类</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/标签/"><span class="header-nav-menu-item__icon"><i class="fas fa-tags"></i></span><span class="header-nav-menu-item__text">标签</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/categories/Book/"><span class="header-nav-menu-item__icon"><i class="fas fa-book"></i></span><span class="header-nav-menu-item__text">书籍</span></a></div></div><div class="header-nav-search"><span class="header-nav-search__icon"><i class="fas fa-search"></i></span><span class="header-nav-search__text">搜索</span></div><div class="header-nav-mode"><div class="mode"><div class="mode-track"><span class="mode-track-moon"></span><span class="mode-track-sun"></span></div><div class="mode-thumb"></div></div></div></div></nav><div class="header-banner"><div class="header-banner-info"><div class="header-banner-info__title">愷龍的网络日志</div><div class="header-banner-info__subtitle">每天多学一点，以后就少敲一点代码</div></div></div></div></header><main class="main" id="main"><div class="main-inner"><div class="content-wrap" id="content-wrap"><div class="content" id="content"><!-- Just used to judge whether it is an article page--><div id="is-post"></div><div class="post"><header class="post-header"><h1 class="post-title">java-Thread</h1><div class="post-meta"><span class="post-meta-item post-meta-item--createtime"><span class="post-meta-item__icon"><i class="far fa-calendar-plus"></i></span><span class="post-meta-item__info">发表于</span><span class="post-meta-item__value">2022-04-02</span></span><span class="post-meta-item post-meta-item--updatetime"><span class="post-meta-item__icon"><i class="far fa-calendar-check"></i></span><span class="post-meta-item__info">更新于</span><span class="post-meta-item__value">2022-04-05</span></span></div></header><div class="post-body"><p>#相关概念</p>
<ul>
<li><p>程序(program)是为完成特定任务、用某种语言编写的一组指令的集合。即指<code>一 段静态的代码</code>，静态对象。</p>
<span id="more"></span></li>
<li><p>进程(process)是程序的一次执行过程，或是<code>正在运行的一个程序</code>。是一个动态的过程：有它自身的产生、存在和消亡的过程。——生命周期<br>⊙如：运行中的QQ，运行中的MP3播放器<br>⊙程序是静态的，进程是动态的<br>⊙<code>进程作为资源分配的单位</code>，系统在运行时会为每个进程分配不同的内存区域   </p>
</li>
<li><p>线程(thread)，进程可进一步细化为线程，是一个程序内部的一条执行路径。<br>⊙若一个进程同一时间 并行执行多个线程，就是支持多线程的<br>⊙<code>线程作为调度和执行的单位，每个线程拥有独立的运行栈和程序计数器(pc)</code>，线程切换的开<br>销小<br>⊙一个进程中的多个线程共享相同的内存单元/内存地址空间它们从同一堆中分配对象，可以<br>访问相同的变量和对象。这就使得线程间通信更简便、高效。但多个线程操作共享的系统资<br>源可能就会带来<code>安全的隐患</code>。    </p>
<center>
<img src="https://pic.imgdb.cn/item/6247ff2d27f86abb2a9097a8.jpg">
</center></li>
<li><p>进程与线程   </p>
</li>
</ul>
<center>
<img src="https://pic.imgdb.cn/item/6247ff6f27f86abb2a913cf8.jpg">
</center>
- 单核CPU 和多核CPU 的理解   
⊙单核CPU，其实是一种假的多线程，因为在一个时间单元内，也只能执行一个线程
的任务。例如：虽然有多车道，但是收费站只有一个工作人员在收费，只有收了费
才能通过，那么CPU就好比收费人员。如果有某个人不想交钱，那么收费人员可以
把他“挂起”（晾着他，等他想通了，准备好了钱，再去收费）。但是因为CPU时
间单元特别短，因此感觉不出来。   
⊙如果是多核的话，才能更好的发挥多线程的效率。（现在的服务器都是多核的）   
⊙一个Java应用程序java.exe，其实至少有三个线程：main()主线程，gc()
垃圾回收线程，异常处理线程。当然如果发生异常，会影响主线程。  
- 并行与并发      
⊙并行：多个CPU同时执行多个任务。比如：多个人同时做不同的事。   
⊙并发：一个CPU(采用时间片)同时执行多个任务。比如：秒杀、多个人做同一件事。   


        <h2 id="使用多线程的优点"   >
          <a href="#使用多线程的优点" class="heading-link"><i class="fas fa-link"></i></a><a href="#使用多线程的优点" class="headerlink" title="使用多线程的优点"></a>使用多线程的优点</h2>
      <p>背景 ： 以单核CPU为例，只使用单个线程先后完成多个任务（调用多个方<br>法），肯定比用多个线程来完成用的时间更短，为何仍需多线程呢？<br>多线程程序的优点：      </p>
<ol>
<li>提高应用程序的响应。对图形化界面更有意义，可增强用户体验。   </li>
<li>提高计算机系统CPU的利用率    </li>
<li>改善程序结构。将既长又复杂的进程分为多个线程，独立运行，利于理解和<br>修改    </li>
</ol>

        <h2 id="何时需要多线程"   >
          <a href="#何时需要多线程" class="heading-link"><i class="fas fa-link"></i></a><a href="#何时需要多线程" class="headerlink" title="何时需要多线程"></a>何时需要多线程</h2>
      <ul>
<li>程序需要同时执行两个或多个任务。</li>
<li>程序需要实现一些需要等待的任务时，如用户输入、文件读写<br>操作、网络操作、搜索等。</li>
<li>需要一些后台运行的程序时。</li>
</ul>

        <h1 id="线程的创建和使用"   >
          <a href="#线程的创建和使用" class="heading-link"><i class="fas fa-link"></i></a><a href="#线程的创建和使用" class="headerlink" title="线程的创建和使用"></a>线程的创建和使用</h1>
      <ul>
<li>Java语言的JVM允许程序运行多个线程，它通过java.lang.Thread<br>类来体现。   </li>
<li>Thread类的特性<br>⊙每个线程都是通过某个特定Thread对象的run()方法来完成操作的，经常<br>把run()方法的主体称为 线程体<br>⊙通过该Thread对象的start()方法来启动这个线程，而非直接调用run()   </li>
</ul>

        <h2 id="Thread类"   >
          <a href="#Thread类" class="heading-link"><i class="fas fa-link"></i></a><a href="#Thread类" class="headerlink" title="Thread类"></a>Thread类</h2>
      <p>Java语言的JVM允许程序运行多个线程，它通过 java. lang.Thread类来体现  </p>
<ul>
<li>构造 器<br>⊙Thread() ：创建新的Thread对象<br>⊙Thread(String threadname)： ：创建线程并指定线程实例名<br>⊙Thread(Runnable target) ：指定创建线程的目标对象，它实现了Runnable接<br>⊙中的run方法<br>⊙Thread(Runnable target, String name) ：创建新的Thread对象</li>
</ul>

        <h2 id="API中创建线程的两种方式"   >
          <a href="#API中创建线程的两种方式" class="heading-link"><i class="fas fa-link"></i></a><a href="#API中创建线程的两种方式" class="headerlink" title="API中创建线程的两种方式"></a>API中创建线程的两种方式</h2>
      
        <h3 id="方式一：继承Thread类的方式："   >
          <a href="#方式一：继承Thread类的方式：" class="heading-link"><i class="fas fa-link"></i></a><a href="#方式一：继承Thread类的方式：" class="headerlink" title="方式一：继承Thread类的方式："></a>方式一：继承Thread类的方式：</h3>
      <ol>
<li>定义子类继承Thread类。   </li>
<li>子类中重写Thread类中的run方法。   </li>
<li>创建Thread子类对象，即创建了线程对象。   </li>
<li>调用线程对象start方法：启动线程，调用run方法。  </li>
</ol>
<p>例： </p>
<figure class="highlight java"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><code class="hljs java"><br><span class="hljs-comment">//1.继承Thread类</span><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyThread</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Thread</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">MyThread</span><span class="hljs-params">()</span> </span>&#123;<br>    &#125;<br><br> <span class="hljs-comment">//2.重run方法</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">100</span>; i++) &#123;<br>            <span class="hljs-keyword">if</span> (i % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>) &#123;<br>                System.out.println(i);<br>            &#125;<br>        &#125;<br>    &#125;<br>&#125;<br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ThreadTest</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br><span class="hljs-comment">//3.新建Thread对象</span><br>        MyThread myThread = <span class="hljs-keyword">new</span> MyThread();<br>        <span class="hljs-comment">//4.调用start方法</span><br>        myThread.start();<br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></div></figure>
<center>
<img src="https://pic.imgdb.cn/item/6248027627f86abb2a97aa0c.jpg">
</center>
<center>
<img src="https://pic.imgdb.cn/item/624802a727f86abb2a9815a1.jpg">
</center>

<ul>
<li>注意点：   </li>
</ul>
<p>1.如果自己手动调用run()方法，那么就只是普通方法，没有启动多线程模式。<br>2.run()方法由JVM调用，什么时候调用，执行的过程控制都有操作系统的CPU<br>调度决定。<br>3.想要启动多线程，必须调用start方法。<br>4.一个线程对象只能调用一次start()方法启动，如果重复调用了，则将抛出以上<br>的异常“IllegalThreadStateException”。    </p>

        <h3 id="方式二：实现Runnable-接口"   >
          <a href="#方式二：实现Runnable-接口" class="heading-link"><i class="fas fa-link"></i></a><a href="#方式二：实现Runnable-接口" class="headerlink" title="方式二：实现Runnable 接口"></a>方式二：实现Runnable 接口</h3>
      <ol>
<li>定义子类，实现Runnable接口。  </li>
<li>子类中重写Runnable接口中的run方法。  </li>
<li>通过Thread类含参构造器创建线程对象。   </li>
<li>将Runnable接口的子类对象作为实际参数传递给Thread类的构造器中。   </li>
<li>调用Thread类的start方法：开启线程，调用Runnable子类接口的run方法。   </li>
</ol>
<p>例：   </p>
<figure class="highlight java"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//1. 创建一个实现了Runnable接口的类</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RunnableTest</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span> </span>&#123;<br>    <span class="hljs-comment">// 2. 实现类去实现Runnable中的抽象方法：run()</span><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">100</span>; i++) &#123;<br>            System.out.println(i);<br>        &#125;<br>    &#125;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">test</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>        <span class="hljs-comment">//3. 创建实现类的对象</span><br>        RunnableTest runnableTest = <span class="hljs-keyword">new</span> RunnableTest();<br>        <span class="hljs-comment">//4. 将此对象作为参数传递到Thread类的构造器中，创建Thread类的对象</span><br>        Thread thread = <span class="hljs-keyword">new</span> Thread(runnableTest);<br>        <span class="hljs-comment">//5. 通过Thread类的对象调用start()</span><br>        thread.start();<br><br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></div></figure>


        <h3 id="两种方式的对比："   >
          <a href="#两种方式的对比：" class="heading-link"><i class="fas fa-link"></i></a><a href="#两种方式的对比：" class="headerlink" title="两种方式的对比："></a>两种方式的对比：</h3>
      <p>开发中优先选择：实现Runnable接口的方式<br>原因：   </p>
<ol>
<li>实现的方式没类的单继承性的局限性   </li>
</ol>
<p>​ 2. 实现的方式更适合来处理多个线程共享数据的情况。   </p>
<p><strong>联系：</strong>public class Thread implements Runnable</p>
<p><strong>相同点：</strong>两种方式都需要重写run(),将线程要执行的逻辑声明在run()中。 目前两种方式，要想启动线程，都是调用的Thread类中的start()。  </p>
<p>也可以采用创建匿名类的方式： </p>
<figure class="highlight java"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ThreadDemo</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br><br>        <span class="hljs-comment">//创建Thread类的匿名子类的方式</span><br>        <span class="hljs-keyword">new</span> Thread() &#123;<br>            <span class="hljs-meta">@Override</span><br>            <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>&#123;<br>                <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">100</span>; i++) &#123;<br>                    <span class="hljs-keyword">if</span> (i % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>) &#123;<br>                        System.out.println(Thread.currentThread().getName() + <span class="hljs-string">&quot;:&quot;</span> + i);<br>                    &#125;<br>                &#125;<br>            &#125;<br>        &#125;.start();<br><br>        <span class="hljs-keyword">new</span> Thread() &#123;<br>            <span class="hljs-meta">@Override</span><br>            <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>&#123;<br>                <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">100</span>; i++) &#123;<br>                    <span class="hljs-keyword">if</span> (i % <span class="hljs-number">2</span> != <span class="hljs-number">0</span>) &#123;<br>                        System.out.println(Thread.currentThread().getName() + <span class="hljs-string">&quot;:&quot;</span> + i);<br>                    &#125;<br>                &#125;<br>            &#125;<br>        &#125;.start();<br><br><br>    &#125;<br>&#125;<br><br><br></code></pre></td></tr></table></div></figure>

        <h2 id="Thread类的常用方法"   >
          <a href="#Thread类的常用方法" class="heading-link"><i class="fas fa-link"></i></a><a href="#Thread类的常用方法" class="headerlink" title="Thread类的常用方法"></a>Thread类的常用方法</h2>
      
        <h3 id="常用方法"   >
          <a href="#常用方法" class="heading-link"><i class="fas fa-link"></i></a><a href="#常用方法" class="headerlink" title="常用方法"></a>常用方法</h3>
      <p>1.void start(): 启动线程，并执行对象的run()方法<br>2.run(): 线程在被调度时执行的操作<br>3.String getName(): 返回线程的名称<br>4.void setName(String name):设置该线程名称<br>5.static Thread currentThread(): 返回当前线程。在Thread子类中就是this，通常用于主线程和Runnable实现类<br>6.static void yield()： ： 线程让步</p>
<blockquote>
<p>①暂停当前正在执行的线程，把执行机会让给优先级相同或更高的线程<br>②若队列中没有同优先级的线程，忽略此方法</p>
</blockquote>
<p>7.join() ： ： 当某个程序执行流中调用其他线程的 join() 方法时，调用线程将<br>被阻塞，直到 join() 方法加入的 join 线程执行完为止   </p>
<blockquote>
<p>低优先级的线程也可以获得执行</p>
</blockquote>
<p>8.static void sleep(long millis) ：(指定时间:毫秒)</p>
<blockquote>
<p>①令当前活动线程在指定时间段内放弃对CPU控制,使其他线程有机会被执行,时间到后<br>重排队。<br>②抛出InterruptedException异常</p>
</blockquote>
<p>9.stop(): 强制线程生命期结束，不推荐使用<br>10.boolean isAlive()： ： 返回boolean，判断线程是否还活着</p>
</div><footer class="post-footer"><div class="post-ending ending"><div class="ending__text">------ 本文结束，感谢您的阅读 ------</div></div><div class="post-copyright copyright"><div class="copyright-author"><span class="copyright-author__name">本文作者: </span><span class="copyright-author__value"><a href="https://kohler19.gitee.io">李恺龙</a></span></div><div class="copyright-link"><span class="copyright-link__name">本文链接: </span><span class="copyright-link__value"><a href="https://kohler19.gitee.io/2022/04/02/java-Thread/">https://kohler19.gitee.io/2022/04/02/java-Thread/</a></span></div><div class="copyright-notice"><span class="copyright-notice__name">版权声明: </span><span class="copyright-notice__value">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en" rel="external nofollow" target="_blank">BY-NC-SA</a> 许可协议。转载请注明出处！</span></div></div><nav class="post-paginator paginator"><div class="paginator-prev"><a class="paginator-prev__link" href="/2022/04/02/java-GUI1/"><span class="paginator-prev__icon"><i class="fas fa-angle-left"></i></span><span class="paginator-prev__text">java-GUI编程之布局类型介绍</span></a></div><div class="paginator-next"><a class="paginator-next__link" href="/2022/03/31/cloud-computing5/"><span class="paginator-prev__text">云计算第七章</span><span class="paginator-next__icon"><i class="fas fa-angle-right"></i></span></a></div></nav></footer></div></div><div class="comments" id="comments"><div id="valine-container"></div></div></div><div class="sidebar-wrap" id="sidebar-wrap"><aside class="sidebar" id="sidebar"><div class="sidebar-nav"><span class="sidebar-nav-toc current">文章目录</span><span class="sidebar-nav-ov">站点概览</span></div><section class="sidebar-toc"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E5%A4%9A%E7%BA%BF%E7%A8%8B%E7%9A%84%E4%BC%98%E7%82%B9"><span class="toc-number">1.</span> <span class="toc-text">
          使用多线程的优点</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%95%E6%97%B6%E9%9C%80%E8%A6%81%E5%A4%9A%E7%BA%BF%E7%A8%8B"><span class="toc-number">2.</span> <span class="toc-text">
          何时需要多线程</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%BA%BF%E7%A8%8B%E7%9A%84%E5%88%9B%E5%BB%BA%E5%92%8C%E4%BD%BF%E7%94%A8"><span class="toc-number"></span> <span class="toc-text">
          线程的创建和使用</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Thread%E7%B1%BB"><span class="toc-number">1.</span> <span class="toc-text">
          Thread类</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#API%E4%B8%AD%E5%88%9B%E5%BB%BA%E7%BA%BF%E7%A8%8B%E7%9A%84%E4%B8%A4%E7%A7%8D%E6%96%B9%E5%BC%8F"><span class="toc-number">2.</span> <span class="toc-text">
          API中创建线程的两种方式</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%96%B9%E5%BC%8F%E4%B8%80%EF%BC%9A%E7%BB%A7%E6%89%BFThread%E7%B1%BB%E7%9A%84%E6%96%B9%E5%BC%8F%EF%BC%9A"><span class="toc-number">2.1.</span> <span class="toc-text">
          方式一：继承Thread类的方式：</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%96%B9%E5%BC%8F%E4%BA%8C%EF%BC%9A%E5%AE%9E%E7%8E%B0Runnable-%E6%8E%A5%E5%8F%A3"><span class="toc-number">2.2.</span> <span class="toc-text">
          方式二：实现Runnable 接口</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%A4%E7%A7%8D%E6%96%B9%E5%BC%8F%E7%9A%84%E5%AF%B9%E6%AF%94%EF%BC%9A"><span class="toc-number">2.3.</span> <span class="toc-text">
          两种方式的对比：</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Thread%E7%B1%BB%E7%9A%84%E5%B8%B8%E7%94%A8%E6%96%B9%E6%B3%95"><span class="toc-number">3.</span> <span class="toc-text">
          Thread类的常用方法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B8%B8%E7%94%A8%E6%96%B9%E6%B3%95"><span class="toc-number">3.1.</span> <span class="toc-text">
          常用方法</span></a></li></ol></li></ol></section><!-- ov = overview--><section class="sidebar-ov hide"><div class="sidebar-ov-author"><div class="sidebar-ov-author__avatar"><img class="sidebar-ov-author__avatar_img" src="https://s4.ax1x.com/2022/01/03/Tb2VW6.png" alt="avatar"></div><p class="sidebar-ov-author__text">格物致知，知行合一</p></div><div class="sidebar-ov-social"><a class="sidebar-ov-social-item" href="https://s4.ax1x.com/2022/01/03/Tb8ZB4.png" target="_blank" rel="noopener" data-popover="微信" data-popover-pos="up"><span class="sidebar-ov-social-item__icon"><i class="fab fa-weixin"></i></span></a><a class="sidebar-ov-social-item" href="mailto:lklong@88.com" target="_blank" rel="noopener" data-popover="social.Email" data-popover-pos="up"><span class="sidebar-ov-social-item__icon">lklong@88.com</span></a></div><div class="sidebar-ov-cc"><a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en" target="_blank" rel="noopener" data-popover="知识共享许可协议" data-popover-pos="up"><img src="/images/cc-by-nc-sa.svg"></a></div></section><div class="sidebar-reading"><div class="sidebar-reading-info"><span class="sidebar-reading-info__text">你已阅读了 </span><span class="sidebar-reading-info__num">0</span><span class="sidebar-reading-info__perc">%</span></div><div class="sidebar-reading-line"></div></div></aside></div><div class="clearfix"></div></div></main><footer class="footer" id="footer"><div class="footer-inner"><div><span>Copyright © 2023</span><span class="footer__icon"><i class="fas fa-heart"></i></span><span>愷龍 All Rights Reserved</span></div><div><span>由 <a href="http://hexo.io/" title="Hexo" target="_blank" rel="noopener">Hexo</a> 强力驱动</span><span> v5.4.0</span><span class="footer__devider">|</span><span>主题 - <a href="https://github.com/liuyib/hexo-theme-stun/" title="Stun" target="_blank" rel="noopener">Stun</a></span><span> v2.6.2</span></div></div></footer><div class="loading-bar" id="loading-bar"><div class="loading-bar__progress"></div></div><div class="back2top" id="back2top"><span class="back2top__icon"><i class="fas fa-rocket"></i></span></div></div><div class="search-mask"></div><div class="search-popup"><span class="search-close"></span><div class="search-input"><input placeholder="搜索文章（支持多关键词，请用空格分隔）"></div><div class="search-results"></div></div><script src="https://cdn.jsdelivr.net/npm/jquery@v3.4.1/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@1.5.2/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@1.5.2/velocity.ui.min.js"></script><script>function initSearch() {
  var isXML = true;
  var search_path = 'search.xml';

  if (!search_path) {
    search_path = 'search.xml';
  } else if (/json$/i.test(search_path)) {
    isXML = false;
  }

  var path = '/' + search_path;
  $.ajax({
    url: path,
    dataType: isXML ? 'xml' : 'json',
    async: true,
    success: function (res) {
      var datas = isXML ? $('entry', res).map(function () {
        // 将 XML 转为 JSON
        return {
          title: $('title', this).text(),
          content: $('content', this).text(),
          url: $('url', this).text()
        };
      }).get() : res;
      var $input = $('.search-input input');
      var $result = $('.search-results');
      // 搜索对象（标题、内容）的权重，影响显示顺序
      var WEIGHT = { title: 100, content: 1 };
      var searchPost = function () {
        var searchText = $input.val().toLowerCase().trim();
        // 根据空白字符分隔关键字
        var keywords = searchText.split(/[\s]+/);
        // 搜索结果
        var matchPosts = [];

        // 有多个关键字时，将原文字整个保存下来
        if (keywords.length > 1) {
          keywords.push(searchText);
        }
        // 防止未输入字符时搜索
        if (searchText.length > 0) {
          datas.forEach(function (data) {
            var isMatch  = false;
            // 没有标题的文章使用预设的 i18n 变量代替
            var title = (data.title && data.title.trim()) || '[ 文章无标题 ]';
            var titleLower = title && title.toLowerCase();
            // 删除 HTML 标签 和 所有空白字符
            var content = data.content && data.content.replace(/<[^>]+>/g, '');
            var contentLower = content && content.toLowerCase();
            // 删除重复的 /
            var postURL = data.url && decodeURI(data.url).replace(/\/{2,}/g, '/');
            // 标题中匹配到的关键词
            var titleHitSlice = [];
            // 内容中匹配到的关键词
            var contentHitSlice = [];

            keywords.forEach(function (keyword) {
              /**
              * 获取匹配的关键词的索引
              * @param {String} keyword 要匹配的关键字
              * @param {String} text 原文字
              * @param {Boolean} caseSensitive 是否区分大小写
              * @param {Number} weight 匹配对象的权重。权重大的优先显示
              * @return {Array}
              */
              function getIndexByword (word, text, caseSensitive, weight) {
                if (!word || !text) {
                  return [];
                };

                var startIndex = 0; // 每次匹配的开始索引
                var index = -1;     // 匹配到的索引值
                var result = [];    // 匹配结果

                if (!caseSensitive) {
                  word = word.toLowerCase();
                  text = text.toLowerCase();
                }

                while((index = text.indexOf(word, startIndex)) !== -1) {
                  var hasMatch = false;
                  // 索引位置相同的关键词，保留长度较长的
                  titleHitSlice.forEach(function (hit) {
                    if (hit.index === index && hit.word.length < word.length) {
                      hit.word = word;
                      hasMatch = true;
                    }
                  });
                  startIndex = index + word.length;
                  !hasMatch && result.push({ index: index, word: word, weight: weight });
                }
                return result;
              }
              titleHitSlice = titleHitSlice.concat(getIndexByword(keyword, titleLower, false, WEIGHT.title));
              contentHitSlice = contentHitSlice.concat(getIndexByword(keyword, contentLower, false, WEIGHT.content));
            });

            var hitTitle = titleHitSlice.length;
            var hitContent = contentHitSlice.length;

            if (hitTitle > 0 || hitContent > 0) {
              isMatch = true;
            }
            if (isMatch) {
              ;[titleHitSlice, contentHitSlice].forEach(function (hit) {
                // 按照匹配文字的索引的递增顺序排序
                hit.sort(function (left, right) {
                  return left.index - right.index;
                });
              });
              /**
              * 给文本中匹配到的关键词添加标记，从而进行高亮显示
              * @param {String} text 原文本
              * @param {Array} hitSlice 匹配项的索引信息
              * @param {Number} start 开始索引
              * @param {Number} end 结束索引
              * @return {String}
              */
              function highlightKeyword (text, hitSlice, start, end) {
                if (!text || !hitSlice || !hitSlice.length) {
                  return;
                }

                var result = '';
                var startIndex = start;
                var endIndex = end;
                hitSlice.forEach(function (hit) {
                  if (hit.index < startIndex) {
                    return;
                  }

                  var hitWordEnd = hit.index + hit.word.length;
                  result += text.slice(startIndex, hit.index);
                  result += '<b>' + text.slice(hit.index, hitWordEnd) + '</b>';
                  startIndex = hitWordEnd;
                });
                result += text.slice(startIndex, endIndex);
                return result;
              }

              var postData = {};
              // 文章总的搜索权重
              var postWeight = titleHitSlice.length * WEIGHT.title + contentHitSlice.length * WEIGHT.content;
              // 标记匹配关键词后的标题
              var postTitle = highlightKeyword(title, titleHitSlice, 0, title.length) || title;
              // 标记匹配关键词后的内容
              var postContent;
              // 显示内容的长度
              var SHOW_WORD_LENGTH = 200;
              // 命中关键词前的字符显示长度
              var SHOW_WORD_FRONT_LENGTH = 20;
              var SHOW_WORD_END_LENGTH = SHOW_WORD_LENGTH - SHOW_WORD_FRONT_LENGTH;

              // 截取匹配的第一个字符，前后共 200 个字符来显示
              if (contentHitSlice.length > 0) {
                var firstIndex = contentHitSlice[0].index;
                var start = firstIndex > SHOW_WORD_FRONT_LENGTH ? firstIndex - SHOW_WORD_FRONT_LENGTH : 0;
                var end = firstIndex + SHOW_WORD_END_LENGTH;
                postContent = highlightKeyword(content, contentHitSlice, start, end);
              } else { // 未匹配到内容，直接截取前 200 个字符来显示
                postContent = content.slice(0, SHOW_WORD_LENGTH);
              }
              postData.title = postTitle;
              postData.content = postContent;
              postData.url = postURL;
              postData.weight = postWeight;
              matchPosts.push(postData);
            }
          });
        }

        var resultInnerHtml = '';
        if (matchPosts.length) {
          // 按权重递增的顺序排序，使权重大的优先显示
          matchPosts.sort(function (left, right) {
            return right.weight - left.weight;
          });
          resultInnerHtml += '<ul>';
          matchPosts.forEach(function (post) {
            resultInnerHtml += '<li><a class="search-results-title" href="' + post.url + '">';
            resultInnerHtml += post.title;
            resultInnerHtml += '</a><div class="search-results-content">';
            resultInnerHtml += post.content;
            resultInnerHtml += '</div></li>';
          });
          resultInnerHtml += '</ul>';
        } else {
          resultInnerHtml += '<div class="search-results-none"><i class="far fa-meh"></i></div>';
        }
        $result.html(resultInnerHtml);
      };
      $input.on('input', searchPost);
      $input.on('keyup', function (e) {
        if (e.keyCode === Stun.utils.codeToKeyCode('Enter')) {
          searchPost();
        }
      });
    }
  });
}

function closeSearch () {
  $('body').css({ overflow: 'auto' });
  $('.search-popup').css({ display: 'none' });
  $('.search-mask').css({ display: 'none' });
}

window.addEventListener('DOMContentLoaded', function () {
  Stun.utils.pjaxReloadLocalSearch = function () {
    $('.header-nav-search').on('click', function (e) {
      e.stopPropagation();
      $('body').css('overflow', 'hidden');
      $('.search-popup')
        .velocity('stop')
        .velocity('transition.expandIn', {
          duration: 300,
          complete: function () {
            $('.search-popup input').focus();
          }
        });
      $('.search-mask')
        .velocity('stop')
        .velocity('transition.fadeIn', {
          duration: 300
        });

      initSearch();
    });
    $('.search-mask, .search-close').on('click', function () {
      closeSearch();
    });
    $(document).on('keydown', function (e) {
      // Escape <=> 27
      if (e.keyCode === Stun.utils.codeToKeyCode('Escape')) {
        closeSearch();
      }
    });
  };

  Stun.utils.pjaxReloadLocalSearch();
}, false);

function safeOpenUrl(url) {
  var newTab = window.open();
  newTab.opener = null;
  newTab.location = url;
}

function extSearch(engine) {
  var engines = {
    google: 'https://www.google.com/search?q=',
    bing: 'https://cn.bing.com/search?q=',
    baidu: 'https://www.baidu.com/s?ie=UTF-8&wd=',
  };
  var host = window.location.host;
  var query = $('.search-input input').val().toLowerCase().trim();
  var uri = engines[engine] + query + ' site:' + host;

  if (query) {
    safeOpenUrl(uri);
  } else {
    Stun.utils.popAlert('warning', '请输入字符');
  }
}

var assistSearchList = window.CONFIG.assistSearch;

if (Array.isArray(assistSearchList)) {
  assistSearchList.forEach(function (name) {
    document.querySelector('.search-btns-item--' + name).addEventListener('click', function () {
      extSearch(name);
    }, false);
  });
}</script><script src="https://cdn.jsdelivr.net/npm/leancloud-storage@latest/dist/av-min.js"></script><script src="https://cdn.jsdelivr.net/npm/valine@latest/dist/Valine.min.js"></script><script>function loadValine () {
  var GUEST_INFO = ['nick', 'mail', 'link'];
  var guest_info = 'nick,mail,link';

  guest_info = guest_info.split(',').filter(function(item) {
    return GUEST_INFO.indexOf(item) > -1;
  });
  new Valine({
    el: '#valine-container',
    appId: 'lxsmJYFBR3TcsTpKPFWSN0HX-gzGzoHsz',
    appKey: 'lW6taHRzBHFtJeWSSzXXMAxH',
    notify: true,
    verify: true,
    placeholder: 'Just go go',
    avatar: 'mp',
    meta: guest_info,
    pageSize: '10' || 10,
    visitor: false,
    recordIP: false,
    lang: '' || 'zh-cn',
    path: window.location.pathname
  });
}

if (false) {
  loadValine();
} else {
  window.addEventListener('DOMContentLoaded', loadValine, false);
}</script><script src="/js/utils.js?v=2.6.2"></script><script src="/js/stun-boot.js?v=2.6.2"></script><script src="/js/scroll.js?v=2.6.2"></script><script src="/js/header.js?v=2.6.2"></script><script src="/js/sidebar.js?v=2.6.2"></script><script type="application/json" src="/search.xml"></script></body></html>